<template>
  <div>
    <div>
      <el-form ref="addform"
               label-width="80px"
               :rules="addFormRules"
               :model="addQuery">
        <el-form-item label="课程名称"
                      prop="course_name">
          <el-input v-model="addQuery.course_name">
          </el-input>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span="16">
            <el-form-item label="课程分类"
                          prop="category_id">
              <el-select v-model="addQuery.category_id"
                         placeholder="请选择">
                <el-option v-for="item in categoryNameOptions"
                           :key="item.category_id"
                           :label="item.category_name"
                           :value="item.category_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="danger"
                       size="mini"
                       @click="showcategoryDialog"
                       icon="el-icon-s-tools">课程分类设置</el-button>
          </el-col>
        </el-row>

        <el-form-item label="排序"
                      prop="sort">
          <el-input v-model="addQuery.sort">
          </el-input>
        </el-form-item>
        <el-form-item label="课程介绍"
                      prop="desc">
          <el-input type="textarea"
                    :rows="2"
                    v-model="addQuery.desc"
                    placeholder="请输入内容">
          </el-input>
        </el-form-item>
        <el-form-item label="课程来源:"
                      prop="type">
          <el-radio-group v-model="addQuery.type">
            <el-radio label="0">图片二维码</el-radio>
            <el-radio label="1">视频源文件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="课程二维码"
                      prop="file_id">
          <el-upload :class="{hide:hideUpload}"
                     :on-remove="handAvatarRemove"
                     :on-change="handleAvatarSuccess"
                     :limit="1"
                     :file-list="fileList"
                     list-type="picture-card"
                     v-model="addQuery.file_id"
                     ref="upload"
                     action="#"
                     name="files"
                     :auto-upload="false"
                     :on-preview="handlePreview">
            <i slot="default"
               class="el-icon-plus"></i>

            <div slot="tip"
                 class="el-upload__tip">
              限制上传一张, 只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%"
                 :src="dialogImageUrl"
                 alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="解锁要求"
                      prop="remark">
          <el-input type="text"
                    v-model="addQuery.remark"></el-input>
        </el-form-item>
        <el-form-item label="状态"
                      prop="status">
          <el-switch style="display: block"
                     v-model="addQuery.status"
                     active-color="#13ce66"
                     inactive-color="#ff4949"
                     active-text="上架"
                     inactive-text="下架">
          </el-switch>
        </el-form-item>
      </el-form>
      <div style="text-align:right">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="submitUpload">确 定</el-button>
      </div>

    </div>

    <!-- 课程分类设置对话框 -->
    <el-dialog title="课程分类设置"
               :visible.sync="categoryDialog"
               width="50%">
      <div>
        <el-button type="primary"
                   style="width:150px">新增</el-button>
        <el-table :data="categoryList"
                  style="margin-top:20px"
                  border>
          <el-table-column label="课程分类"
                           prop="category_name"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type=" text"
                         size="small">编辑</el-button>
              <el-button type="text"
                         size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadFileRequest } from '@/api/system/upload'
import { addCourseList, categoryList } from '@/api/system/training'
//状态(0下  1上)
const StatusOption = [
  { value: 0, label: false },
  { value: 1, label: true }
]
export default {
  created () {
    this.getcategoryList()
  },
  filters: {
    Type (key) {
      const val = {
        '课程二维码': 0,
        '视频源文件': 1
      }
      return val[key]
    }
  },
  data () {
    //自定义校验
    var sort = (rule, value, callback) => {
      if (value > 20) {
        callback(new Error('排序不能大于20'));
      }
    };
    return {
      fileList: [],
      StatusOption,
      dialogImageUrl: "",
      dialogVisible: false,
      categoryDialog: false,
      categoryNameOptions: [],
      categoryList: "",
      hideUpload: false,
      addQuery: {
        course_name: "",
        category_id: "",
        type: "",
        status: "",
        sort: "",
        desc: "",
        file_id: "",
        remark: ""
      },
      addFormRules: {
        course_name: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        category_id: [
          { required: true, message: '请选择课程分类', trigger: 'change' }
        ],
        sort: [
          { required: true, message: '请输入排序号', trigger: 'blur' },
          { required: true, validator: sort, trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择课程来源', trigger: 'change' }
        ],
        remark: [
          { required: true, message: '请输入解锁要求', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },


    }

  },
  methods: {
    handAvatarRemove () {
      this.hideUpload = false
    },
    handleAvatarSuccess (res, file) {
      console.log(res, 111111111111111111);
      if (res.name) {
        this.hideUpload = true
        // this.addQuery.file_id = res.id
        let formData = new FormData();
        this.fileList.forEach((e) => {
          formData.append("file", e.raw);
        })
        formData.append("dir", "avtive");
        uploadFileRequest(formData).then((res) => {
          console.log(res);
          if (res.data.code == '200') {
            this.addQuery.file_id = res.data.data.file_id
          } else {
            this.$message.warning(res.data.msg)
          }
        })

      } else {
        this.hideUpload = false
        this.$message.error(`图片上传失败:${res.message}`)
      }
    },
    //提交
    submitUpload () {
      // new 一个 FormData()
      // let formData = new FormData();
      // this.fileList.forEach((e) => {
      // 遍历上传的图片数组，把每个图片的文件流 添加进 formData中
      //   formData.append("file", e.raw);
      // });
      // 这里可以添加需要上传的其他参数字段；
      // 注意：formData.append的值只能是字符串或者blob（File）格式, 复杂的数组或者对象的数据无法添加
      // formData.append("dir", "avtive");
      // uploadFileRequest(formData).then((res) => {
      //   console.log(res);
      // if (res.data.code == '200') {
      //   this.addQuery.file_id = res.data.data.file_id
      addCourseList(this.addQuery).then((res) => {
        if (res.data.code == '200') {
          this.$message.success("新增成功")
          this.$emit("closeAddDialog")
        } else {
          this.$message.error(res.data.msg)
        }
      })
      // } else {
      //   this.$message.warning(res.data.msg)
      // }
      // });

    },

    showcategoryDialog () {
      this.categoryDialog = true
    },
    fileOnRemove (file, fileList) {
      this.fileList = fileList;
    },
    fileOnChange (file, fileList) {
      this.fileList = fileList;
    },
    handlePreview (file) {
      // console.log(file, "点击放大");
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //获取分类名称内容
    getcategoryList () {
      categoryList().then((res) => {
        console.log(res);
        this.categoryNameOptions = res.data.data.list
        this.categoryList = res.data.data.list
        console.log(this.categoryNameOptions);
      })
    }

  }

}
</script>

<style>
.hide .el-upload--picture-card {
  display: none;
}
</style>